﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Sinacor.OMM.HFTMessageManager.ProcessLogic
{
    public class HFTLastIdFileManager : IDisposable
    {
        const int MSG_ID_SIZE = 19;

        private FileStream _fileStream;
        string _filePath;

        public HFTLastIdFileManager(string filePath)
        {
            _filePath = filePath;
            OpenOrCreateFile();
        }

        private void OpenOrCreateFile()
        {

            try
            {
                if(!Directory.Exists(Path.GetDirectoryName(_filePath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(_filePath));

                _fileStream = new FileStream(_filePath, FileMode.OpenOrCreate);
            }
            catch (Exception ex)
            {
                //TODO: Log
                throw ex;
            }

        }

        public void Dispose()
        {
            try
            {
                if (_fileStream != null)
                {
                    _fileStream.Flush();
                    _fileStream.Close();
                    _fileStream.Dispose();
                }
            }
            catch (Exception ex)
            {
                //TODO: Log
                throw ex;
            }

        }

        public void WriteLastMsgId(string lastMsgId)
        {
            string strLastMsg = lastMsgId.PadLeft(19, "0".ToCharArray()[0]);
            _fileStream.Position = 0;
            _fileStream.Write(Encoding.Default.GetBytes(strLastMsg), 0, strLastMsg.Length);
            _fileStream.Flush();
        }

        public Int64 ReadLastMsgId()
        {

            Int64 ret;
            byte[] buffer;

            try
            {
                buffer = new byte[MSG_ID_SIZE];

                if (_fileStream.Length == MSG_ID_SIZE)
                {
                    _fileStream.Read(buffer, 0, MSG_ID_SIZE);
                    _fileStream.Flush();
                    ret = Convert.ToInt64(Encoding.Default.GetString(buffer));
                }
                else
                {
                    Dispose();
                    File.Delete(_filePath);
                    OpenOrCreateFile();
                    ret = 0;
                }
            }
            catch (Exception ex)
            {
                //TODO: Log
                throw ex;
            }

            return ret;
        }
    }
}
